﻿using System;
using System.Collections.Generic;
using System.Xml;
using System.Web.Mvc;

namespace NOSDC.Extensions
{
    public interface IRss
    {
        string Title { get; }
        string Description { get; }
        string Link { get; }  
    }

    public class RssResult : ActionResult
    {
        private readonly List<IRss> _items;
        private readonly string _title;
        private readonly string _description;

        /// <summary>
        /// Initialises the RssResult
        /// </summary>
        /// <param name="items">The items to be added to the rss feed.</param>
        /// <param name="title">The title of the rss feed.</param>
        /// <param name="description">A short description about the rss feed.</param>
        public RssResult(IEnumerable<IRss> items, string title, string description)
        {
            _items = new List<IRss>(items);
            _title = title;
            _description = description;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            var settings = new XmlWriterSettings
                               {
                                   Indent = true, 
                                   NewLineHandling = NewLineHandling.Entitize
                               };

            context.HttpContext.Response.ContentType = "text/xml";
            using (var writer = XmlWriter.Create(context.HttpContext.Response.OutputStream, settings))
            {

                // Begin structure
                writer.WriteStartElement("rss");
                writer.WriteAttributeString("version", "2.0");
                writer.WriteStartElement("channel");

                writer.WriteElementString("title", _title);
                writer.WriteElementString("description", _description);
                writer.WriteElementString("link", context.HttpContext.Request.Url.GetLeftPart(UriPartial.Authority));

                // Individual items
                _items.ForEach(x =>
                {
                    writer.WriteStartElement("item");
                    writer.WriteElementString("title", x.Title);
                    writer.WriteElementString("description", x.Description);
                    writer.WriteElementString("link", context.HttpContext.Request.Url.GetLeftPart(UriPartial.Authority) + x.Link);
                    writer.WriteEndElement();
                });

                // End structure
                writer.WriteEndElement();
                writer.WriteEndElement();
            }
        }
    }
}